package com.ds.infrastructure.audit.client.track;

import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSON;
import com.ds.infrastructure.audit.common.entity.KbaBehaviorWrapper;
import com.ds.infrastructure.audit.common.exception.KbaAuditException;
import lombok.extern.slf4j.Slf4j;

import java.util.HashMap;
import java.util.Map;

/**
 * 作用：
 *
 * @author WeiShaoying
 * @date 2020/7/27
 */
@Slf4j
public class KbaProtocolTrackHttp extends AbstractKbaTrack {

    private int timeOut = 3000;

    public KbaProtocolTrackHttp(String server) {
        super(server);
    }

    public KbaProtocolTrackHttp(String server, String appName, String appKey) {
        super(server, appName, appKey);
    }

    /**
     * 初始化
     */
    @Override
    public void initialize() {
    }

    /**
     * Kba上报
     *
     * @param wrapper
     * @throws KbaAuditException
     */
    @Override
    public void report0(KbaBehaviorWrapper wrapper) throws KbaAuditException {
        Map<String, Object> params = new HashMap<>(1);
        params.put("behavior", JSON.toJSONString(wrapper));
        try {
            String response = HttpUtil.post(server, params, timeOut);
            log.info(response);
        } catch (Throwable e) {
            log.error(e.getMessage(), e);
            throw new KbaAuditException(e.getMessage(), e);
        }
    }

    /**
     * 上报并指定回调处理
     *
     * @param wrapper
     * @param callback
     * @throws KbaAuditException
     */
    @Override
    public void report0(KbaBehaviorWrapper wrapper, KbaCallback callback) throws KbaAuditException {
        Map<String, Object> params = new HashMap<>(1);
        params.put("behavior", JSON.toJSONString(wrapper));
        try {
            callback.preProcess();
            String response = HttpUtil.post(server, params, timeOut);
            log.info(response);
            callback.onSuccess(response);
        } catch (Throwable throwable) {
            log.error(throwable.getMessage(), throwable);
            callback.onError(throwable);
            throw new KbaAuditException(throwable.getMessage(), throwable);
        }
    }
}
